package com.bw.parkingspace_module.parkingedit

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bw.parkingspace_module.databinding.ActivityParkingeditBinding
import com.bw.parkingspace_module.parking.entity.ParkingValueEntity
import com.bw.parkingspace_module.parkingedit.adapter.ParkingEditColorAdapter
import com.bw.parkingspace_module.parkingedit.adapter.ParkingImageAdapter
import com.bw.parkingspace_module.parkingedit.entity.*
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.kf.common.entity.EventBusEntity
import com.kf.common.entity.EventBusType
import com.kf.common.mvi.view.BaseActivity
import com.nanchen.compresshelper.CompressHelper
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

@Route(path = "/parking/parkingeditactivity")
class ParkingEditActivity : BaseActivity<ActivityParkingeditBinding, ParkingEditViewModel>(),
    OnItemClickListener {

    @Autowired
    lateinit var parkingEntity: ParkingValueEntity//接收车位申请页面item值
    lateinit var colorAdapter: ParkingEditColorAdapter//颜色适配器
    lateinit var imageAdapter: ParkingImageAdapter//图片适配器
    var imgs = ArrayList<ImageEntity>()//图片集合
    var color: Int = -1//临时变量存储颜色
    var simpleDateFormat = SimpleDateFormat("MM月dd日")//时间转换器

    override fun createViewModel(): ParkingEditViewModel {
        return viewModels<ParkingEditViewModel>().value
    }

    override fun createViewBind(): ActivityParkingeditBinding {
        return ActivityParkingeditBinding.inflate(inflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        BarUtils.setStatusBarColor(this, Color.parseColor("#2196F3"))
        EventBus.getDefault().register(this)
        ARouter.getInstance().inject(this)
        mViewModel.requestColor()//请求颜色接口
        mViewModel.requestDept()//请求所属部门接口
        initBind()//接收服务器返回值
        initColorRecycler()//初始化颜色recycler
        initImageRecycler()//初始化图片recycler
        initClickListener()//点击事件
        initData()//初始化该页面数据
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    //初始化图片recycler
    private fun initImageRecycler() {
        mView.parkingImageRecycler.layoutManager =
            LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        imageAdapter = ParkingImageAdapter()
        mView.parkingImageRecycler.adapter = imageAdapter
        imageAdapter.setNewInstance(imgs)
    }

    //初始化该页面数据
    private fun initData() {
        var currentTimeMillis = System.currentTimeMillis()
        var simpleDateFormat = SimpleDateFormat("yyyy-MM-dd")
        var format = simpleDateFormat.format(currentTimeMillis)
        mView.ParkingEditUserDate.setText(format)
        mView.ParkingEditUserName.text = SPUtils.getInstance().getString("userName", "hxw")
    }

    //点击事件
    private fun initClickListener() {
        //关闭页面
        mView.parkingeditBack.setOnClickListener {
            finish()
        }
        //提交申请车位
        mView.addCartCommit.setOnClickListener {
            if (color == -1) {
                ToastUtils.showShort("请选择颜色")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(mView.ParkingEditUserNum.text.toString())) {
                ToastUtils.showShort("请输入车牌号")
                return@setOnClickListener
            }
            if (mView.requestStartTime.text.equals("选择开始日期")) {
                ToastUtils.showShort("请选择开始日期")
                return@setOnClickListener
            }
            if (mView.requestEndTime.text.equals("选择结束日期")) {
                ToastUtils.showShort("请选择结束日期")
                return@setOnClickListener
            }
            var entity = CarEntity()
            entity.carNum = mView.ParkingEditUserNum.text.toString()
            entity.colorId = color
            entity.parkId = parkingEntity.parkId

            var data = imageAdapter.data as ArrayList

            var parkingEditEntity = ParkingEditEntity()

            var startTime = simpleDateFormat.parse(mView.requestStartTime.text.toString())
            var endTime = simpleDateFormat.parse(mView.requestEndTime.text.toString())

            parkingEditEntity.parkId = parkingEntity.parkId
            parkingEditEntity.parkName = SPUtils.getInstance().getString("userName", "hxw")
            parkingEditEntity.parkStart = startTime.time.toString()
            parkingEditEntity.parkEnd = endTime.time.toString()
            parkingEditEntity.parkTime = System.currentTimeMillis().toString()
            parkingEditEntity.parkUser = SPUtils.getInstance().getInt("userId",-1)
            mViewModel.requestCar(entity, data, parkingEditEntity)
        }
        //开始时间选择器点击事件
        mView.requestStartTime.setOnClickListener {
            TimePickerBuilder(this, object : OnTimeSelectListener {
                override fun onTimeSelect(date: Date?, v: View?) {
                    var format = simpleDateFormat.format(date)
                    var substring = format.substring(0, 2)
                    var substrings = format.substring(3, 5)
                    if (substring.toInt() < 10)
                        substring = substring.removeRange(0, 1)
                    if (substrings.toInt() < 10)
                        substrings = substrings.removeRange(0, 1)
                    mView.requestStartTime.setText("${substring}月${substrings}日")
                }
            }).build().show()
        }
        //结束时间选择器点击事件
        mView.requestEndTime.setOnClickListener {
            TimePickerBuilder(this, object : OnTimeSelectListener {
                override fun onTimeSelect(date: Date?, v: View?) {
                    var format = simpleDateFormat.format(date)
                    var substring = format.substring(0, 2)
                    var substrings = format.substring(3, 5)
                    if (substring.toInt() < 10)
                        substring = substring.removeRange(0, 1)
                    if (substrings.toInt() < 10)
                        substrings = substrings.removeRange(0, 1)
                    mView.requestEndTime.setText("${substring}月${substrings}日")
                }
            }).build().show()
        }
        //添加展示图片点击事件
        mView.addImage.setOnClickListener {
            var data = imageAdapter.data
            if (data.size <= 5)
                PictureSelector.create(this, PictureSelector.SELECT_REQUEST_CODE).selectPicture()
            else
                ToastUtils.showShort("只能选择六张图片哦")

        }
    }

    //初始化颜色recycler
    private fun initColorRecycler() {
        mView.colorRecycler.layoutManager =
            LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        colorAdapter = ParkingEditColorAdapter()
        colorAdapter.setOnItemClickListener(this)
        mView.colorRecycler.adapter = colorAdapter
    }

    //接收服务器返回值
    private fun initBind() {
        lifecycleScope.launch(Dispatchers.Main) {
            mViewModel.mutableContainer
                .uiStateFlow
                .collect {
                    if (it.deptEntity!!.statuesCode == 200) {
                        mView.ParkingDept.setText(it.deptEntity.values!!.get(0).departmentName)
                    }
                    if (it.colorEntity!!.statuesCode == 200) {
                        colorAdapter.setNewInstance(it.colorEntity!!.values as ArrayList<ColorEntity>?)
                    }
                }
        }
    }

    //颜色适配器点击事件
    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        var colorAdapters = adapter as ParkingEditColorAdapter
        var data = colorAdapters.data
        color = Color.parseColor(data.get(position).colorValue)
        mView.preView.setBackgroundColor(color)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PictureSelector.SELECT_REQUEST_CODE && data != null) {
            val pictureBean: PictureBean? = data.getParcelableExtra(PictureSelector.PICTURE_RESULT)
            val bitmap = CompressHelper.getDefault(this).compressToFile(File(pictureBean!!.path))
            LogUtils.e(bitmap.length())
            var path = bitmap.path
            LogUtils.e(bitmap.path)
            var imageEntity = ImageEntity()
            imageEntity.imgPath = path
            var data1 = imageAdapter.data
            data1.add(imageEntity)
            imageAdapter.notifyItemChanged(data1.size - 1)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun eventBus(eventBusEntity: EventBusEntity) {
        if (eventBusEntity.action == EventBusType.PARKING_SUCCESS) {
            finish()
        }
    }
}